package com.creative.accountsdk.holder;

import android.app.Dialog;
import android.content.Intent;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.creative.accountsdk.AccountActivity;
import com.creative.accountsdk.AccountAgreementActivity;
import com.creative.accountsdk.AccountSdk;
import com.creative.accountsdk.AccountUtils;
import com.creative.accountsdk.DataCenter;
import com.creative.accountsdk.DialogUtils;
import com.creative.accountsdk.OnLoginListener;
import com.creative.accountsdk.R;
import com.creative.accountsdk.UserData;
import com.creative.accountsdk.UserInfor;
import com.creative.accountsdk.net.XHttpHandler;
import com.creative.accountsdk.net.account.RegisteProtocol;
import com.creative.util.DataUtil;
import com.creative.util.XTextWatcher;

import cz.msebera.android.httpclient.Header;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by yinjialiang on 15-6-23.
 */
public class RegisteHolder extends BaseHolder{
    private EditText editTextUsername, editTextPassword, editTextNickname;
    private Button buttonOK;
    private TextView tvCreateChild;

    private boolean  toCreateChildAccount = false;

    public RegisteHolder (boolean CreateChildAccount ) {
        toCreateChildAccount = CreateChildAccount;
    }

    public RegisteHolder () {

    }


    @Override
    protected void initViews() {
        editTextUsername = (EditText) viewRoot.findViewById(R.id.editTextUsername);
        editTextPassword = (EditText) viewRoot.findViewById(R.id.editTextPassword);
        editTextNickname = (EditText) viewRoot.findViewById(R.id.editTextNickname);
        tvCreateChild = (TextView)viewRoot.findViewById(R.id.tvCreateChild);
        if (toCreateChildAccount) tvCreateChild.setVisibility(View.VISIBLE);


        InputFilter[] filters = {new NameLengthFilter(activity,16,activity.getString(R.string.account_nickname_length))};
        editTextNickname.setFilters(filters);
        buttonOK = (Button)viewRoot.findViewById(R.id.buttonOK);
        buttonOK.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                registe();
            }
        });

        initThirdLogin();
        //text watcher
        TextWatcher textWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(editTextUsername.getText().toString().equals("") || editTextPassword.getText().toString().equals(""))
                {
                 //   buttonOK.setEnabled(false);
                }
                else
                {
                  //  buttonOK.setEnabled(true);
                }
            }
        };
        editTextNickname.addTextChangedListener(textWatcher);
        editTextUsername.addTextChangedListener(textWatcher);
        editTextPassword.addTextChangedListener(textWatcher);
    }

    private void initThirdLogin()
    {
        if(DataCenter.isForeign())
        {

        }
        else
        {

        }
    }

    private void registe()
    {
        String username = editTextUsername.getText().toString().trim();
        String password = editTextPassword.getText().toString().trim();

        if(TextUtils.isEmpty(editTextNickname.getText().toString())){
            Toast.makeText(activity, R.string.account_nikename_empty, Toast.LENGTH_SHORT).show();
            return ;
        }
        else if (username.equals("")) {
            Toast.makeText(activity, R.string.account_username_empty, Toast.LENGTH_SHORT).show();
            return ;
        }
        else if(!AccountUtils.isValidEmail(username))
        {
            Toast.makeText(activity, R.string.account_invalid_email, Toast.LENGTH_SHORT).show();
            return;
        }
        else if (isvalidpassword(password)<0) {
            int  val = isvalidpassword(password);
            int  tostMsg =R.string.account_password_empty;
             if(val==-2){
                tostMsg = R.string.chinesepassword;
            }
            Toast.makeText(activity,tostMsg,Toast.LENGTH_SHORT).show();
            return ;
        } else if (username.length() < 6) {
            Toast.makeText(activity, R.string.account_username_length, Toast.LENGTH_SHORT).show();
            return ;
        } else if (username.length() > 50) {
            Toast.makeText(activity, R.string.account_username_maxlength, Toast.LENGTH_SHORT).show();
            return ;
        }else if (password.length() < 6) {
            Toast.makeText(activity, R.string.account_password_length, Toast.LENGTH_SHORT).show();
            return ;
        }else if (password.length() > 50) {
            Toast.makeText(activity, R.string.account_password_maxlength, Toast.LENGTH_SHORT).show();
            return ;
        } else {
            final Dialog progress = DialogUtils.createProgress(activity);
            progress.show();

            if (!toCreateChildAccount) {
                final RegisteProtocol protocol = new RegisteProtocol(username, password, editTextNickname.getText().toString());
                protocol.debugUrl(DataCenter.getHttpClient());

                DataCenter.getHttpClient().post(protocol.getUrl(), protocol.getParams(), new XHttpHandler(activity, progress) {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                        super.onSuccess(statusCode, headers, response);
                        progress.cancel();
                        if (protocol.parse(response, activity)) {
                            UserData.getInstance().init(protocol.jsonUser);
                            UserData.getInstance().write(activity);
                            OnLoginListener loginListener = AccountSdk.getInstance().getLoginListener();
                            if (loginListener != null) {
                                loginListener.onComplete(protocol.jsonUser);
                            }
                        }
                        toSelectIdentity();
                    }
                });
            } else {
                final ParentCreateAndBindChildProtocol protocol = new ParentCreateAndBindChildProtocol(username, password, editTextNickname.getText().toString());
                protocol.debugUrl(DataCenter.getHttpClient());

                DataCenter.getHttpClient().post(protocol.getUrl(), protocol.getParams(), new XHttpHandler(activity, progress) {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                        super.onSuccess(statusCode, headers, response);
                        progress.cancel();
                        if (protocol.parse(response, activity)) {
                            if (protocol.jsonKids != null) {
                                String ktoken = protocol.jsonKids.optString("ktoken");
                                String kuid = protocol.jsonKids.optString("kuid");
                                UserInfor info = null;
                                JSONArray ja = protocol.jsonKids.optJSONArray("kids");
                                if (ja != null && ja.length() > 0) {
                                    int kid_num = ja.length();
                                    for (int i = 0; i < kid_num; i++) {
                                        JSONObject jo = ja.optJSONObject(i);
                                        if (jo != null) {
                                            if (kuid.equals(jo.optString("uid"))) {
                                                info = new UserInfor();
                                                info.setJsonToVo(jo);
                                                break;
                                            }
                                        }
                                    }
                                }

                                if (info != null && !TextUtils.isEmpty(kuid)) {
                                    goToChidUserInfo(ktoken, info);
                                }
                            }

                        }
                    }
                });

            }
        }
    }

    private void  toSelectIdentity(){
        activity.hideHolder();
        activity.showHolder(new SelectIdentityHolder());
    }

    private int isvalidpassword(String password) {
        if(TextUtils.isEmpty(password)){
            return -3; // Password must be between 6 and 20 characters.
        }
        int isize = password.length();
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(password);
        if(m.matches()){
            return -2;
        }
        for(int i = 0; i < isize; i++) {
            int icode = password.codePointAt(i);
            if(icode <= 0x9fa5 && icode >= 0x4e00) {
                return -2;
            }
        }
        return 1;
    }

    @Override
    public int getLayoutResID() {
        return R.layout.account_registe;
    }

    @Override
    public void resizeBigger() {

    }

    @Override
    public void resizeSmaller() {

    }

    private void goToChidUserInfo(String toking, UserInfor kiduserinfo) {
        activity.hideHolder();
        activity.userInfoHolder = new UserInfoHolder(activity, kiduserinfo, toking);
        activity.showHolder(activity.userInfoHolder);

    }
}
